from django.shortcuts import render_to_response
from models import CargoAcademico
from forms import CargoAcademicoForm
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.utils import simplejson
from django.core.urlresolvers import reverse
from django.views.generic.create_update import update_object, create_object , delete_object
from django.views.generic.list_detail import object_list

def inicio(request):
    request.breadcrumbs('Cargos',request.path)
    return object_list(request,
        queryset = CargoAcademico.objects.all().order_by('Jerarquia', 'Cargo'),
        allow_empty = True,
        template_name = 'cargo/listarCargos.html'
    )

def obtenerCargo(request , object_id):
    if int(object_id):
        try:
            objecto = CargoAcademico.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto cargo'
    else:
        return 'No existe el objecto cargo'
    return objecto

def verCargo (request, object_id):
    cargo = obtenerCargo(request, object_id)
    if cargo == 'No existe el objecto cargo':
        return render_to_response('error.html',{'error':'No existe el objecto cargo', 'archivo': 'view de cargoAcademico', 'linea': 'linea 16'})
    list_poseedores = cargo.Usuarios.all()
    return render_to_response('cargo/detalles.html', {'cargo': cargo, 'list_poseedores': list_poseedores, 'user': request.user})

def crear(request):
    request.breadcrumbs([('Cargos Academicos',reverse(inicio)),('Crear',request.path)])
    return create_object(request,
        form_class = CargoAcademicoForm,
        template_name = 'cargo/cargo.html',
        post_save_redirect = '/comunidadcyt/cargos'
    )

def editar(request, object_id=0):
    request.breadcrumbs([('Cargos Academicos',reverse(inicio)),('Editar',request.path)])
    return update_object(request,
        model = CargoAcademico,
        form_class = CargoAcademicoForm,
        object_id = object_id,
        template_name = 'cargo/cargo.html',
        post_save_redirect = '/comunidadcyt/cargos'
    )

def borrar(request, object_id=0):
    request.breadcrumbs([('Cargos Academicos',reverse(inicio)),('Borrar',request.path)])
    return delete_object(request,
        model = CargoAcademico,
        template_name = 'cargo/confirm_delete.html',
        post_delete_redirect = '/comunidadcyt/cargos',
        object_id = object_id
    )


def ajax_list_cargos_view(request,key_xhr):
    response_dict = {}
    list = []
    u = CargoAcademico.objects.all().order_by('Jerarquia', 'Cargo')
    for c in u:
        list.append(c.Cargo)
    response_dict.update({'list':list})
    return HttpResponse(simplejson.dumps(response_dict),mimetype = 'application/javascript')

def ajax_create_cargo_view(request,key_xhr):
    response_dict = {}
    
    nc = request.POST.getlist('cargo')
    
    try:
        c = CargoAcademico.objects.get(Cargo__exact = nc[0])
        response_dict.update({'errors':True})
    except ObjectDoesNotExist:
        no = CargoAcademico(Cargo = nc[0])
        no.save()
        response_dict.update({'ok':True})
        response_dict.update({'id':no.id})
        response_dict.update({'cargo':no.Cargo})
    
    return HttpResponse(simplejson.dumps(response_dict),mimetype='application/javascript')

def ajax_list_selected_cargo_view(request,key_xhr):
    response_dict = {}
    lookup_field = request.POST.__getitem__('cargo')
    
    cl = CargoAcademico.objects.filter(Cargo__icontains = lookup_field).order_by('Jerarquia', 'Cargo')
    upl = []
    rl = []
    for c in cl:
        upl.append(c.Usuarios.all())
         
    for ep in upl:
        if ep != []:
            for p in ep:
                if not rl.__contains__(p.user.get_full_name()):
                    rl.append(p.user.get_full_name())
    
    response_dict.update({'list':rl})
    
    return HttpResponse(simplejson.dumps(response_dict),mimetype = 'application/javascript')